<?php
/**
 * GiteeImageSaver 插件的 Action 类
 * 
 * @package GiteeImageSaver
 * @author 星野集xingyeji.com
 * @version 1.0.6
 * @license MIT
 */

if (!defined('__TYPECHO_ROOT_DIR__')) exit;
class GiteeImageSaver_Action extends Typecho_Widget implements Widget_Interface_Do
{
    /**
     * 上传测试图片
     * 
     * @access public
     * @return void
     */
    public function uploadTest()
    {
        // 检查用户权限
        $user = Typecho_Widget::widget('Widget_User');
        if (!$user->pass('administrator')) {
            $this->response->redirect(Typecho_Common::url('dashboard', $this->options->adminUrl));
        }
        
        // 获取插件配置
        try {
            $options = Helper::options()->plugin('GiteeImageSaver');
            if (!$options) {
                throw new Exception('无法获取插件配置');
            }
        } catch (Exception $e) {
            $this->widget('Widget_Notice')->set(_t('获取插件配置失败：%s', $e->getMessage()), 'error');
            $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
            return;
        }
        
        // 检查是否有文件上传
        if (isset($_FILES['testImage']) && $_FILES['testImage']['error'] == 0) {
            // 检查文件类型
            $allowedTypes = array('image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp');
            if (!in_array($_FILES['testImage']['type'], $allowedTypes)) {
                $this->widget('Widget_Notice')->set(_t('请上传有效的图片文件（JPEG, PNG, GIF, BMP, WEBP）'), 'error');
                $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
            }
            
            // 获取保存路径和URL前缀
            list($savePath, $urlPrefix) = $this->getSavePathAndUrlPrefix($options);
            
            // 生成文件名
            $filename = 'test_' . time() . '_' . md5($_FILES['testImage']['name']) . '.png';
            
            // 添加站点标识前缀（如果有）
            if (!empty($options->siteIdentifier)) {
                $filename = $options->siteIdentifier . $filename;
            }
            
            $remotePath = $savePath . '/' . $filename;
            
            // 从仓库地址中提取用户名和仓库名
            $repoPath = parse_url($options->giteeRepo, PHP_URL_PATH);
            $repoPath = trim($repoPath, '/');
            list($owner, $repoName) = explode('/', $repoPath);
            
            // 使用指定的分支，默认为master
            $branch = !empty($options->giteeBranch) ? $options->giteeBranch : 'master';
            
            // 读取文件内容并进行 base64 编码
            $content = file_get_contents($_FILES['testImage']['tmp_name']);
            $contentBase64 = base64_encode($content);
            
            // 检查令牌是否存在
            if (empty($options->giteeToken)) {
                $this->widget('Widget_Notice')->set(_t('Gitee私人令牌为空，无法上传图片'), 'error');
                $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
                return;
            }
            
            // 构建 API URL
            $apiUrl = "https://gitee.com/api/v5/repos/{$owner}/{$repoName}/contents/{$remotePath}";
            
            // 构建请求数据
            $data = array(
                'access_token' => $options->giteeToken,
                'content' => $contentBase64,
                'message' => 'Upload test image via GiteeImageSaver plugin',
                'branch' => $branch
            );
            
            // 发送 POST 请求
            $ch = curl_init($apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            
            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlError = curl_error($ch);
            curl_close($ch);
            
            // 检查cURL错误
            if ($result === false) {
                $this->widget('Widget_Notice')->set(_t('cURL请求失败：%s', $curlError), 'error');
                $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
                return;
            }
            
            if ($httpCode >= 200 && $httpCode < 300) {
                $imageUrl = $urlPrefix . '/' . $filename;
                $this->widget('Widget_Notice')->set(_t('测试图片上传成功！图片URL：%s', $imageUrl), 'success');
            } else {
                $this->widget('Widget_Notice')->set(_t('测试图片上传失败！HTTP代码：%d，响应内容：%s', $httpCode, $result), 'error');
            }
        } else {
            $this->widget('Widget_Notice')->set(_t('请选择一个图片文件进行上传测试'), 'error');
        }
        
        $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
    }
    
    /**
     * 测试 Gitee 配置
     * 
     * @access public
     * @return void
     */
    public function testConfig()
    {
        // 检查用户权限
        $user = Typecho_Widget::widget('Widget_User');
        if (!$user->pass('administrator')) {
            $this->response->redirect(Typecho_Common::url('dashboard', $this->options->adminUrl));
        }
        
        // 获取插件配置
        try {
            $options = Helper::options()->plugin('GiteeImageSaver');
            if (!$options) {
                throw new Exception('无法获取插件配置');
            }
        } catch (Exception $e) {
            $this->widget('Widget_Notice')->set(_t('获取插件配置失败：%s', $e->getMessage()), 'error');
            $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
            return;
        }
        
        // 从仓库地址中提取用户名和仓库名
        try {
            if (empty($options->giteeRepo)) {
                throw new Exception('Gitee仓库地址为空');
            }
            
            $repoPath = parse_url($options->giteeRepo, PHP_URL_PATH);
            if (!$repoPath) {
                throw new Exception('无效的仓库地址格式');
            }
            
            $repoPath = trim($repoPath, '/');
            $repoParts = explode('/', $repoPath);
            
            if (count($repoParts) < 2) {
                throw new Exception('仓库地址格式错误，无法提取用户名和仓库名');
            }
            
            $owner = $repoParts[0];
            $repoName = $repoParts[1];
            
            if (empty($owner) || empty($repoName)) {
                throw new Exception('无法从仓库地址中提取有效的用户名或仓库名');
            }
        } catch (Exception $e) {
            $this->widget('Widget_Notice')->set(_t('解析仓库地址失败：%s', $e->getMessage()), 'error');
            $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
            return;
        }
        
        // 使用指定的分支，默认为master
        $branch = !empty($options->giteeBranch) ? $options->giteeBranch : 'master';
        
        // 构建 API URL 检查仓库是否存在
        $apiUrl = "https://gitee.com/api/v5/repos/{$owner}/{$repoName}?access_token=" . urlencode($options->giteeToken);
        
        // 发送 GET 请求
        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        // 检查cURL错误
        if ($result === false) {
            $this->widget('Widget_Notice')->set(_t('cURL请求失败：%s', $curlError), 'error');
            $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
            return;
        }
        
        if ($httpCode == 200) {
            // 检查分支是否存在
            $apiUrl = "https://gitee.com/api/v5/repos/{$owner}/{$repoName}/branches/{$branch}?access_token=" . urlencode($options->giteeToken);
            
            $ch = curl_init($apiUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            
            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlError = curl_error($ch);
            curl_close($ch);
            
            // 检查cURL错误
            if ($result === false) {
                $this->widget('Widget_Notice')->set(_t('检查分支时cURL请求失败：%s', $curlError), 'error');
                $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
                return;
            }
            
            if ($httpCode == 200) {
                $this->widget('Widget_Notice')->set(_t('Gitee配置测试成功！仓库和分支 %s 连接正常。', $branch), 'success');
            } else {
                $this->widget('Widget_Notice')->set(_t('Gitee仓库连接正常，但分支 %s 不存在或无法访问。', $branch), 'error');
            }
        } else {
            $this->widget('Widget_Notice')->set(_t('Gitee配置测试失败！HTTP代码：%d，响应内容：%s', $httpCode, $result), 'error');
        }
        
        $this->response->redirect(Typecho_Common::url('extending.php?panel=GiteeImageSaver%2Ftest.php', $this->options->adminUrl));
    }
    
    /**
     * 获取保存路径和URL前缀
     * 
     * @access private
     * @param object $options 插件配置
     * @return array [保存路径, URL前缀]
     */
    private function getSavePathAndUrlPrefix($options)
    {
        // 基础路径和URL前缀
        $basePath = rtrim($options->imagePath, '/');
        
        // 获取URL前缀并替换分支名称
        $baseUrlPrefix = rtrim($options->imageUrlPrefix, '/');
        if (!empty($options->giteeBranch) && $options->giteeBranch != 'master') {
            // 替换URL前缀中的分支名称
            $baseUrlPrefix = preg_replace('/\/raw\/[^\/]+\//', '/raw/' . $options->giteeBranch . '/', $baseUrlPrefix);
        }
        
        // 检查是否使用日期文件夹
        if ($options->useDateFolder == '1') {
            // 获取当前日期，用于创建日期文件夹
            $dateFolder = date('Y/m/d');
            
            // 构建完整的保存路径和URL前缀
            $savePath = $basePath . '/' . $dateFolder;
            $urlPrefix = $baseUrlPrefix . '/' . $dateFolder;
        } else {
            // 不使用日期文件夹
            $savePath = $basePath;
            $urlPrefix = $baseUrlPrefix;
        }
        
        return [$savePath, $urlPrefix];
    }
    
    /**
     * 执行方法
     * 
     * @access public
     * @return void
     */
    public function action()
    {
        $this->on('upload-test')->uploadTest();
        $this->on('test-config')->testConfig();
    }
}